﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zocono.Infrastructure.Common;
using Zocono.WCS.Domain.DomainRepository;
using Zocono.WCS.Domain.EntityInfo;
using Zocono.WCS.Domain.PlcBytesObject;

namespace Zocono.WCS.Domain.EquipmentProcessDomain.PlanarMessage
{
    public class PlanarStateBOMessageService : IPlanarStateMessageService
    {
        private readonly ILogUtil _LogUtil;
        private readonly ISnowflake _Snowflake;
        private readonly IDispatchEquipmentPlanarStateRepository _dispatchEquimentPlanarStateRepository;
        //private readonly IRedisHelper _IRedisHelper;

        public PlanarStateBOMessageService(ILogUtil logUtil
         , ISnowflake snowflake
         , IDispatchEquipmentPlanarStateRepository dispatchEquimentPlanarStateRepository
         , IDispatchEquipmentRepository dispatchEquipmentRepository
         /*, IRedisHelper redisHelper*/)
        {
            _LogUtil = logUtil;
            _Snowflake = snowflake;
            _dispatchEquimentPlanarStateRepository = dispatchEquimentPlanarStateRepository;
            //_IRedisHelper = redisHelper;

        }
        public async Task ProcessStateMessageAsync(BytesObjectBase planarStateMessage/*, BytesObjectBase plcStateMassge*/)
        {
            /*
            * 处理逻辑
            * 1. 状态报文服务
            * 2. Plc在线离线报文
            * 3. 根据设备编号查询调度设备是否存在，存在走第四步，反之返回提示
            * 4. 根据设备ID查询是否存在设备状态记录，存在则对比其他属性值，属性值一样则不做操作，反之Insert、存入redis
            */
            PlanarGeneralPlcActionBO plannerPlcStateBo = null;
            PlanarGeneralWcsActionBO plannerWcsStateBo = null;
            if (planarStateMessage.ObjectType.Contains("Plc"))
            {
                plannerPlcStateBo = planarStateMessage as PlanarGeneralPlcActionBO;
            }
            else if (planarStateMessage.ObjectType.Contains("Wcs"))
            {
                plannerWcsStateBo = planarStateMessage as PlanarGeneralWcsActionBO;
            }
            //var plcStateBo = plcStateMassge as PlcOnLineStateBO;//Plc在线离线报文 没有设备信息

            if (plannerPlcStateBo == null && plannerWcsStateBo == null /*|| plcStateBo == null*/)
            {
                _LogUtil.Info($"[状态报文服务]处理失败：参数异常");
                return;
            }

            ////redis获取平面调度设备状态信息
            //var equimentPlanarStateInfo = _IRedisHelper.GetStringKey<DispatchEquipmentPlanarState>(plannerWcsStateBo.EquipmentCode.ToString());


            DispatchEquipmentPlanarState modelPlc = null;

            modelPlc = await _dispatchEquimentPlanarStateRepository.GetFirstAsync(l => l.EquipmentCode == plannerPlcStateBo.EquipmentCode
            &&( l.MessageType == plannerPlcStateBo.ObjectType|| l.MessageType == plannerWcsStateBo.ObjectType));
            if (modelPlc == null)
            {
                await InsertDispatchEquipmentPlanarState(plannerPlcStateBo, plannerWcsStateBo);
            }
            else
            {
                await UpdateDispatchEquipmentPlanarState(plannerPlcStateBo, plannerWcsStateBo);
            }
            //根据设备号搜索数据库中对应的数据，如若没有则插入，有则更新


        }

        /// <summary>
        /// Insert平面调度设备状态、存入redis
        /// </summary>
        /// <param name="plannerStateBo">平面状态报文服务</param>
        /// <param name="plcStateBo">Plc在线离线报文</param>
        private async Task InsertDispatchEquipmentPlanarState(PlanarGeneralPlcActionBO plcActionBO, PlanarGeneralWcsActionBO wcsActionBO)
        {
            DispatchEquipmentPlanarState model = new DispatchEquipmentPlanarState();
            string key = string.Empty;
            if (plcActionBO != null)
            {
                model.PlanerStateID = _Snowflake.GetId();
                model.EquipmentCode = plcActionBO.EquipmentCode;
                model.TaskCode = plcActionBO.TaskCode;
                model.ToPosition = plcActionBO.ToEquipmentCode.ToString();
                model.PalletCode = plcActionBO.PalletBarcode;
                model.AlrmCode = plcActionBO.AlrmCode;
                model.Yuliu1 = plcActionBO.Reserve;
                model.Yuliu2 = plcActionBO.Reserve2;
                model.Yuliu3 = plcActionBO.Reserve3;
                model.Yuliu4 = plcActionBO.Reserve4;
                model.MessageType = plcActionBO.ObjectType;
                model.UpdateTime = DateTime.Now;
                key = plcActionBO.EquipmentCode.ToString();


            }
            else if (wcsActionBO!=null)
            {
                model.PlanerStateID = _Snowflake.GetId();
                model.EquipmentCode = wcsActionBO.EquipmentCode;
                model.TaskCode = wcsActionBO.TaskCode;
                model.ToPosition = wcsActionBO.ToEquipmentCode.ToString();
                model.PalletCode = wcsActionBO.PalletBarcode;
                model.AlrmCode = wcsActionBO.AlrmCode;
                model.Yuliu1 = wcsActionBO.Reserve;
                model.Yuliu2 = wcsActionBO.Reserve2;
                model.Yuliu3 = wcsActionBO.Reserve3;
                model.Yuliu4 = wcsActionBO.Reserve4;
                model.MessageType = wcsActionBO.ObjectType;
                model.UpdateTime = DateTime.Now;
                key = wcsActionBO.EquipmentCode.ToString();
            }

            #region redis操作
            //存入redis
            //string values = JsonConvert.SerializeObject(model);
            ////插入redis
            //bool bo = _IRedisHelper.SetStringKey(key, values);

            //if (!bo)
            //    _LogUtil.Info($"[状态报文服务]存入redis失败：设备{key})");

            #endregion

            //存入数据库
            await _dispatchEquimentPlanarStateRepository.InsertAsync(model);


        }



        /// <summary>
        /// Insert平面调度设备状态、存入redis
        /// </summary>
        /// <param name="plannerStateBo">平面状态报文服务</param>
        /// <param name="plcStateBo">Plc在线离线报文</param>
        private async Task UpdateDispatchEquipmentPlanarState(PlanarGeneralPlcActionBO plcActionBO, PlanarGeneralWcsActionBO wcsActionBO)
        {
            DispatchEquipmentPlanarState model = null;

            string key=string.Empty;
            if (plcActionBO != null)
            {
                model = await _dispatchEquimentPlanarStateRepository.GetFirstAsync(l => l.EquipmentCode == plcActionBO.EquipmentCode
                &&l.MessageType==plcActionBO.ObjectType);
                model.TaskCode = plcActionBO.TaskCode;
                model.ToPosition = plcActionBO.ToEquipmentCode.ToString();
                model.PalletCode = plcActionBO.PalletBarcode;
                model.AlrmCode = plcActionBO.AlrmCode;
                model.Yuliu1 = plcActionBO.Reserve;
                model.Yuliu2 = plcActionBO.Reserve2;
                model.Yuliu3 = plcActionBO.Reserve3;
                model.Yuliu4 = plcActionBO.Reserve4;
                model.UpdateTime = DateTime.Now;
                key= plcActionBO.EquipmentCode.ToString();


            }
            else if (wcsActionBO != null)
            {
                model = await _dispatchEquimentPlanarStateRepository.GetFirstAsync(l => l.EquipmentCode == plcActionBO.EquipmentCode
                && l.MessageType == wcsActionBO.ObjectType);
                model.TaskCode = wcsActionBO.TaskCode;
                model.ToPosition = wcsActionBO.ToEquipmentCode.ToString();
                model.PalletCode = wcsActionBO.PalletBarcode;
                model.AlrmCode = wcsActionBO.AlrmCode;
                model.Yuliu1 = wcsActionBO.Reserve;
                model.Yuliu2 = wcsActionBO.Reserve2;
                model.Yuliu3 = wcsActionBO.Reserve3;
                model.Yuliu4 = wcsActionBO.Reserve4;
                model.UpdateTime = DateTime.Now;
                key = wcsActionBO.EquipmentCode.ToString();
            }

            #region redis操作
            ////存入redis
            //string values = JsonConvert.SerializeObject(model);
            ////插入redis
            //bool bo = _IRedisHelper.SetStringKey(key, values);

            //if (!bo)
            //    _LogUtil.Info($"[状态报文服务]存入redis失败：设备{key})");

            #endregion

            //存入数据库
            await _dispatchEquimentPlanarStateRepository.UpdateAsync(model);


        }
    }
}
